package com.cnbm.wcsbasic.protocol.netty.modbus.entity;


import com.cnbm.wcsbasic.protocol.netty.io.common.byteutils.ByteUtils;
import com.cnbm.wcsbasic.protocol.netty.io.common.enmuc.ModbusFC;
import com.cnbm.wcsbasic.protocol.netty.io.common.enmuc.PlcVarType;

import java.util.List;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2024-04-23 9:23
 */

public class WriteRequestFrame {
    private MBAP mbap;
    //功能码 1
    private byte functionCode;
    //寄存器起始地址 2
    private byte[] address;
    //寄存器数量 2
    private byte[] unitNum;
    //寄存器数据字节长度 1
    private byte unitByteNum;
    //寄存器数据
    private byte[] newValue;

    public WriteRequestFrame(Integer unitId, ModbusFC fc, PlcVarType plcVarType, Integer address, Object newValue) {
        //要被写入的数据，转为byte[]
        this.newValue = plcVarType.toBytes(newValue);
        //功能码
        this.functionCode = fc.getFwrite();
        //开始读的数据的地址。从00 00开始读数据  寄存器起始地址
        this.address = ByteUtils.intToBytes(address);
        //寄存器数 2个字节
        this.unitNum = ByteUtils.remainders(this.newValue.length);
        //寄存器数据字节长度 1个字节   this.unitByteNum = this.unitNum * 2
        this.unitByteNum = ByteUtils.usintTo1Byte(ByteUtils.toInt(this.unitNum[0],this.unitNum[1])*2);

        this.mbap = new MBAP(
                ByteUtils.intToBytes(7+this.unitByteNum),
                ByteUtils.sintToBytes(unitId)[0]
        );
    }

    public String getTransationId(){
        return mbap.getTransationId();
    }

    public byte[] toBytes(){
        List<Byte> bytes = mbap.toBytes();
        bytes.add(functionCode);
        //寄存器起始地址
        bytes.add(address[0]);
        bytes.add(address[1]);
        //寄存器数量
        bytes.add(unitNum[0]);
        bytes.add(unitNum[1]);
        //寄存器数据字节长度
        bytes.add(unitByteNum);
        //寄存器数据
        //Byte.toUnsignedInt(unitByteNum)
        Integer length = ByteUtils.toInt(unitByteNum);

        for(int i=0;i<length;i++){
            if(i>=newValue.length){
                bytes.add((byte)0x00);
            }else {
                bytes.add(newValue[i]);
            }
        }

        byte[] result = new byte[bytes.size()];
        for(int i=0;i<bytes.size();i++){
            result[i] = bytes.get(i);
        }
        return result;

    }

}
